import React, { useState, useRef } from 'react';
import { 
  Box, 
  Typography, 
  Button, 
  Paper, 
  Divider,
  Alert,
  Snackbar,
  CircularProgress
} from '@mui/material';
import SchedulerManager from './SchedulerManager';
import DownloadIcon from '@mui/icons-material/Download';
import UploadIcon from '@mui/icons-material/Upload';
import ExportData from './ExportData';
import { importService } from '../services/exportOrImportService';
import { useUser } from '../contexts/UserContext';

const Management = () => {
  const [exportOpen, setExportOpen] = useState(false);
  const [importStatus, setImportStatus] = useState(null); // 'success', 'error', 'loading'
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: '',
    severity: 'info'
  });
  const fileInputRef = useRef(null);
  const { updateContacts, updateCurrentUser } = useUser();

  // 处理导出数据按钮点击
  const handleExportClick = () => {
    setExportOpen(true);
  };

  // 处理导出对话框关闭
  const handleExportClose = () => {
    setExportOpen(false);
  };

  // 处理导入按钮点击
  const handleImportClick = () => {
    fileInputRef.current.click();
  };

  // 处理文件选择
  const handleFileSelect = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    try {
      setImportStatus('loading');
      
      // 使用importService导入文件
      await importService.importFile(file, updateCurrentUser, updateContacts);
      
      setImportStatus('success');
      setSnackbar({
        open: true,
        message: '数据导入成功！',
        severity: 'success'
      });
    } catch (error) {
      console.error('导入数据失败:', error);
      setImportStatus('error');
      setSnackbar({
        open: true,
        message: `导入数据失败: ${error.message}`,
        severity: 'error'
      });
    } finally {
      // 清空文件输入，以便可以重新选择同一文件
      event.target.value = '';
      // 3秒后重置状态
      setTimeout(() => {
        setImportStatus(null);
      }, 3000);
    }
  };

  // 处理Snackbar关闭
  const handleSnackbarClose = (event, reason) => {
    if (reason === 'clickaway') return;
    setSnackbar({ ...snackbar, open: false });
  };

  return (
    <Box sx={{ 
      height: '100%', 
      width: '100%', 
      bgcolor: '#f5f5f5',
      p: 3,
      overflow: 'auto'
    }}>
      <Typography variant="h5" component="h1" gutterBottom>
        管理
      </Typography>
      
      <SchedulerManager />
      
      <Paper sx={{ p: 3, mb: 3 }}>
        <Typography variant="h7" gutterBottom>
          数据管理
        </Typography>
        <Divider sx={{ mb: 2 }} />
        
        <Box sx={{ display: 'flex', justifyContent: 'space-between', width: '100%', px: 1 }}>
          <Button
            variant="contained"
            color="primary"
            size="small"
            startIcon={<DownloadIcon />}
            onClick={handleExportClick}
            sx={{ 
              maxWidth: '120px', 
              fontSize: '0.85rem',
              py: 0.8,
              px: 1.5
            }}
          >
            导出
          </Button>
          
          <Button
            variant="outlined"
            color="primary"
            size="small"
            startIcon={importStatus === 'loading' ? <CircularProgress size={16} /> : <UploadIcon />}
            onClick={handleImportClick}
            disabled={importStatus === 'loading'}
            sx={{ 
              maxWidth: '120px', 
              fontSize: '0.85rem',
              py: 0.8,
              px: 1.5
            }}
          >
            {importStatus === 'loading' ? '导入中...' : '导入'}
          </Button>
          
          <input
            type="file"
            accept=".json"
            ref={fileInputRef}
            style={{ display: 'none' }}
            onChange={handleFileSelect}
          />
        </Box>
        
        {importStatus === 'success' && (
          <Alert severity="success" sx={{ mt: 2 }}>
            数据导入成功！
          </Alert>
        )}
        
        {importStatus === 'error' && (
          <Alert severity="error" sx={{ mt: 2 }}>
            导入数据失败，请确保文件格式正确。
          </Alert>
        )}
      </Paper>
      
      <ExportData open={exportOpen} onClose={handleExportClose} />
      
      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={handleSnackbarClose}
      >
        <Alert onClose={handleSnackbarClose} severity={snackbar.severity}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default Management;